package com.example.service.impl;

import com.example.entity.vo.request.AiDrawVo;
import com.example.entity.vo.request.MetaDataVo;
import com.example.service.NFTService;
import com.example.utils.IPFSUtil;
import com.tencentcloudapi.aiart.v20221229.AiartClient;
import com.tencentcloudapi.aiart.v20221229.models.ResultConfig;
import com.tencentcloudapi.aiart.v20221229.models.TextToImageRequest;
import com.tencentcloudapi.aiart.v20221229.models.TextToImageResponse;
import jakarta.annotation.Resource;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

@Service
public class NFTServiceImpl implements NFTService {

    @Resource
    private IPFSUtil ipfsUtil;

    @Resource
    private AiartClient aiartClient;

    /**
     * 将前端传来的文件，上传到IPFS中
     * @param multipartFile 前端传来的图片文件
     * @return 错误信息，null为正常
     */
    @Override
    public String uploadIPFS(MultipartFile multipartFile) {
        try {
            //返回结果hash
            //访问：http://localhost:8081/ipfs/hash
            return ipfsUtil.add(multipartFile);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    @Override
    public String uploadIPFS(MetaDataVo vo) {
        //返回结果hash
        //访问：http://localhost:8081/ipfs/hash
        return ipfsUtil.addJson(vo);
    }
    @SneakyThrows
    @Override
    public String aiDraw(AiDrawVo vo) {
        //请求参数
        TextToImageRequest textToImageRequest = new TextToImageRequest();
        textToImageRequest.setLogoAdd(0L); //不添加水印
        textToImageRequest.setRspImgType("url"); //图片返回值，默认是base64，这里选择URL地址
//        textToImageRequest.setStyles("201".split(",")); //这里图片风格默认是201，动漫风，203是古风古典 401是写实
        ResultConfig resultConfig = new ResultConfig();
        resultConfig.setResolution("1080:1920"); //分辨率设置
        textToImageRequest.setResultConfig(resultConfig);
        textToImageRequest.setPrompt(vo.getKeyword());//提示词

        //发起图片生成请求
        TextToImageResponse textToImageResponse = aiartClient.TextToImage(textToImageRequest);
        String apiUrl = textToImageResponse.getResultImage();

        //保存到IPFS
        return saveToIPFS(apiUrl);
    }
    // 保存图片到IPFS并返回IPFS URL
    private String saveToIPFS(String url) throws Exception {
        byte[] imageData = downloadImage(url);  // 下载图片数据
        return uploadToIpfs(imageData);  // 上传图片到IPFS并返回IPFS URL
    }
    // 下载图像并以字节数组形式返回
    private static byte[] downloadImage(String imageUrl) throws Exception {
        URL url = new URL(imageUrl);
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();
        conn.setRequestMethod("GET");
        InputStream in = conn.getInputStream();
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int n = 0;
        while ((n = in.read(buffer)) != -1) {
            out.write(buffer, 0, n);
        }
        in.close();
        return out.toByteArray();
    }
    // 将数据上传到IPFS并返回IPFS URL
    private String uploadToIpfs(byte[] data) throws IOException {
        InputStream inputStream = new ByteArrayInputStream(data);
        String ipfsUrl = ipfsUtil.add(inputStream);
        inputStream.close();
        return ipfsUrl;
    }
}
